{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d15b3c6c-58a8-4dff-a99c-79f4a7ffbe76",
   "metadata": {
    "@deathbeds/jupyterlab-fonts": {
     "styles": {
      "": {
       "body[data-jp-deck-mode='presenting'] &": {
        "height": null,
        "left": null,
        "position": null,
        "top": null,
        "width": null,
        "zoom": null
       }
      }
     }
    },
    "editable": true,
    "jupyterlab-slideshow": {
     "layer": null
    },
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "# Python快速上手"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e23a1c89cc2a0b32",
   "metadata": {
    "@deathbeds/jupyterlab-fonts": {
     "styles": {
      "": {
       "body[data-jp-deck-mode='presenting'] &": {
        "z-index": "1"
       }
      }
     }
    },
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 核心数据类型"
   ]
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": "print(\"hello world\")",
   "id": "a8a13603f8de4102",
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "id": "ad61198bc8e391dc",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "# python中变量不需要声明类型\n",
    "\n",
    "int_val = 42  # 整型\n",
    "\n",
    "float_val = 3.1415  # 浮点型\n",
    "\n",
    "is_training = True  # 布尔型\n",
    "\n",
    "text = \"Hello, Zhouyu!\"  # 字符串\n",
    "\n",
    "tuple_val = (16, 768, 123, 1234)  # 元组\n",
    "\n",
    "list_val = [32, 64, 128, 128]  # 列表 List\n",
    "\n",
    "set_val = {\"CPU\", \"GPU\"}  # Set\n",
    "\n",
    "dict_val = {\"EOS\": 50256, \"EOS1\": 502561}  # 字典 Map Key-Value\n",
    "\n",
    "print(int_val, float_val, is_training, text, tuple_val, list_val, set_val, dict_val)"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": "dict_val.get(\"EOS1\")",
   "id": "258bc76af73927a3",
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "markdown",
   "id": "241acd9d-01d5-4c6f-9398-f190de9a4f9f",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 运算符"
   ]
  },
  {
   "cell_type": "code",
   "id": "4b8525a646254128",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "a = 10\n",
    "\n",
    "print(a + 3)\n",
    "\n",
    "print(a - 3)\n",
    "\n",
    "print(a * 3)\n",
    "\n",
    "print(a / 3)\n",
    "\n",
    "print(a % 3)  # 取余数 1\n",
    "\n",
    "print(a // 3)  # 取整除 商 3\n",
    "\n",
    "print(a ** 2)  # 平方\n",
    "\n",
    "print(4 ** 0.5)  # 开平方"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "markdown",
   "id": "365693c8e950dcb8",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 运算符重载"
   ]
  },
  {
   "cell_type": "code",
   "id": "2d59f51a-b4eb-4fef-b491-722fa98ee62e",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "class Custom:\n",
    "    def __init__(self, value):\n",
    "        self.value = value\n",
    "\n",
    "    # 重载 + 运算符\n",
    "    def __add__(self, other):\n",
    "        return self.value * other.value\n",
    "\n",
    "    # # matrix mul\n",
    "    # def __matmul__(self, other):\n",
    "    #     return self.value + other.value\n",
    "\n",
    "\n",
    "a = Custom(3)\n",
    "b = Custom(4)\n",
    "\n",
    "c = a @ b\n",
    "print(c)"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "markdown",
   "id": "eb6bca3bf71cebaa",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 无穷大\n",
    "在 Python 中，inf（无穷大）和 nan（非数字）是浮点数（float）类型的特殊值，用于处理数学计算中的边界情况"
   ]
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": "float('inf')",
   "id": "f6617abc9e1e88c5",
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "id": "e84177e79e22e43c",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "pos_inf = float('inf')  # 正无穷\n",
    "\n",
    "neg_inf = float('-inf')  # 负无穷\n",
    "\n",
    "print(pos_inf)\n",
    "print(neg_inf)\n",
    "\n",
    "print(pos_inf * -1)\n",
    "\n",
    "print(pos_inf > 10000)\n",
    "print(neg_inf < -10000)"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "markdown",
   "id": "bb1527cc56e523e3",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 非数字nan"
   ]
  },
  {
   "cell_type": "code",
   "id": "d0f4939b801d4638",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "import math\n",
    "\n",
    "a = float('nan')\n",
    "print(a)\n",
    "\n",
    "# 比如某个人的年龄是未知的，那么就可以用nan替代\n",
    "data = [1, 2, float('nan'), 4]\n",
    "print(data)\n",
    "\n",
    "cleaned = [x for x in data if not math.isnan(x)]\n",
    "print(cleaned)"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "markdown",
   "id": "3b81175a66715a84",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 字符串高级操作"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b1f5992b1465e727",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 字符串格式化"
   ]
  },
  {
   "cell_type": "code",
   "id": "97662d2c99c1ca52",
   "metadata": {},
   "source": [
    "name = \"zhouyu\"\n",
    "age = 18\n",
    "\n",
    "print(f\"{name} is {age} years old.\")\n",
    "\n",
    "print(\"{} is {} years old.\".format(name, age))\n",
    "\n",
    "print(\"%s is %d years old.\" % (name, age))"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "markdown",
   "id": "7d006359cd28a0d1",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 字符串查找"
   ]
  },
  {
   "cell_type": "code",
   "id": "1683dd83f46986f8",
   "metadata": {},
   "source": [
    "s = \"hello world\"\n",
    "\n",
    "print(s.find(\"world1\"))  # 返回索引 6，找不到返回 -1\n",
    "\n",
    "print(s.index(\"world1\"))  # 类似 find()，但找不到会报错"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "markdown",
   "id": "a030f1fb60783838",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "正则表达式"
   ]
  },
  {
   "cell_type": "code",
   "id": "52fc969888fd158e",
   "metadata": {},
   "source": [
    "import re\n",
    "\n",
    "text = \"Python 3.10\"\n",
    "match = re.search(r\"\\d+\\.\\d+\", text)  # 匹配数字版本\n",
    "print(match.group())  # 输出 3.10"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "markdown",
   "id": "24a9904c4f458582",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "查看python版本"
   ]
  },
  {
   "cell_type": "code",
   "id": "10f9f2194b246b81",
   "metadata": {},
   "source": [
    "import sys\n",
    "\n",
    "print(sys.version)"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "markdown",
   "id": "94127eed55bd738a",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 字符串分割与连接"
   ]
  },
  {
   "cell_type": "code",
   "id": "cfcbc27dfa2048d1",
   "metadata": {},
   "source": [
    "s = \"I love python\"\n",
    "\n",
    "parts = s.split()  # 默认就是按空格切分\n",
    "\n",
    "print(parts)"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "id": "866dfca6ebdf07bf",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T10:35:10.352579Z",
     "start_time": "2025-06-13T10:35:10.349005Z"
    }
   },
   "source": [
    "lines = \"line1\\nline2\\nline3\"\n",
    "\n",
    "print(lines.splitlines())  # ['line1', 'line2', 'line3']"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['line1', 'line2', 'line3']\n"
     ]
    }
   ],
   "execution_count": 58
  },
  {
   "cell_type": "code",
   "id": "9eb5432d8cd5f9f2",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T10:35:20.960454Z",
     "start_time": "2025-06-13T10:35:20.956705Z"
    }
   },
   "source": [
    "words = [\"I\", \"love\", \"python\"]\n",
    "\n",
    "print(\" \".join(words))"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I love python\n"
     ]
    }
   ],
   "execution_count": 59
  },
  {
   "cell_type": "markdown",
   "id": "308acfce66a17648",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 字符串对齐与填充"
   ]
  },
  {
   "cell_type": "code",
   "id": "577e339d1f2f9f43",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": [],
    "ExecuteTime": {
     "end_time": "2025-06-13T10:35:54.008002Z",
     "start_time": "2025-06-13T10:35:54.005566Z"
    }
   },
   "source": [
    "s = \"Python\"\n",
    "print(s.ljust(10, \"-\"))\n",
    "print(s.rjust(10, \"-\"))\n",
    "print(s.center(11, \"*\"))"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Python----\n",
      "----Python\n",
      "***Python**\n"
     ]
    }
   ],
   "execution_count": 61
  },
  {
   "cell_type": "code",
   "id": "db506df0e539ac02",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T10:36:01.318709Z",
     "start_time": "2025-06-13T10:36:01.314793Z"
    }
   },
   "source": [
    "print(\"42\".zfill(5))"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "00042\n"
     ]
    }
   ],
   "execution_count": 62
  },
  {
   "cell_type": "markdown",
   "id": "3e79b8dd68137e04",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 移除空白/特定字符"
   ]
  },
  {
   "cell_type": "code",
   "id": "87bf0ab9ee79087",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T10:36:28.296935Z",
     "start_time": "2025-06-13T10:36:28.294833Z"
    }
   },
   "source": [
    "s = \"  python  \"\n",
    "print(s.rstrip())  # \"python\"\n",
    "print(s.lstrip())  # \"python  \"\n",
    "print(s.strip())"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  python\n",
      "python  \n",
      "python\n"
     ]
    }
   ],
   "execution_count": 64
  },
  {
   "cell_type": "markdown",
   "id": "9dccc086a4393e04",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 列表高级操作"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2afb63e1e10a7258",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 切片操作"
   ]
  },
  {
   "cell_type": "code",
   "id": "423434c730ae239e",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T10:43:46.182233Z",
     "start_time": "2025-06-13T10:43:46.179267Z"
    }
   },
   "source": [
    "my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
    "\n",
    "print(my_list[-1])\n",
    "\n",
    "print(my_list[2:7])  # 左开右闭区间, 左开右闭（注意：这里反了，应该是左闭右开，闭表示包含）\n",
    "\n",
    "print(my_list[2:])  # 从索引2开始到末尾\n",
    "\n",
    "print(my_list[:2])  # 从索引0开始到索引5结束，不包括5，相当于取数组的前5条记录\n",
    "\n",
    "print(my_list[-2:])  # 获取最后一个元素\n",
    "\n",
    "print(my_list[1::2])  # 步长为2"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "9\n",
      "[2, 3, 4, 5, 6]\n",
      "[2, 3, 4, 5, 6, 7, 8, 9]\n",
      "[0, 1]\n",
      "[8, 9]\n",
      "[1, 3, 5, 7, 9]\n"
     ]
    }
   ],
   "execution_count": 89
  },
  {
   "cell_type": "code",
   "id": "8caf09c55b2d8705",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": [],
    "ExecuteTime": {
     "end_time": "2025-06-13T10:44:20.573211Z",
     "start_time": "2025-06-13T10:44:20.566687Z"
    }
   },
   "source": [
    "# 修改切片\n",
    "my_list[2:5] = [20, 30, 40]\n",
    "print(my_list)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0, 1, 20, 30, 40, 5, 6, 7, 8, 9]\n"
     ]
    }
   ],
   "execution_count": 90
  },
  {
   "cell_type": "code",
   "id": "1a6a03eb38640205",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": [],
    "ExecuteTime": {
     "end_time": "2025-06-13T10:44:39.811755Z",
     "start_time": "2025-06-13T10:44:39.807947Z"
    }
   },
   "source": [
    "# 删除切片\n",
    "my_list[2:5] = []\n",
    "print(my_list)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0, 1, 5, 6, 7, 8, 9]\n"
     ]
    }
   ],
   "execution_count": 91
  },
  {
   "cell_type": "markdown",
   "id": "aa00325e9e8656f4",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 列表排序"
   ]
  },
  {
   "cell_type": "code",
   "id": "c2fd7418c5ebfdb0",
   "metadata": {},
   "source": [
    "# 基本排序\n",
    "numbers = [3, 1, 4, 1, 5, 9, 2]\n",
    "numbers.sort()\n",
    "print(numbers)"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T10:45:35.075698Z",
     "start_time": "2025-06-13T10:45:35.071960Z"
    }
   },
   "cell_type": "code",
   "source": [
    "words = [\"apple\", \"banana\", \"cherry\", \"date\"]\n",
    "words.sort()\n",
    "print(words)"
   ],
   "id": "67760af20b2da8ae",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['apple', 'banana', 'cherry', 'date']\n"
     ]
    }
   ],
   "execution_count": 92
  },
  {
   "cell_type": "code",
   "id": "28ff5c95a44e3b92",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": [],
    "ExecuteTime": {
     "end_time": "2025-06-13T10:45:43.966515Z",
     "start_time": "2025-06-13T10:45:43.962560Z"
    }
   },
   "source": [
    "# 自定义排序\n",
    "words = [\"apple\", \"banana\", \"cherry\", \"date\"]\n",
    "words.sort(key=len)  # 按长度排序\n",
    "print(words)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['date', 'apple', 'banana', 'cherry']\n"
     ]
    }
   ],
   "execution_count": 93
  },
  {
   "cell_type": "code",
   "id": "c99c6aed28600cc5",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": [],
    "ExecuteTime": {
     "end_time": "2025-06-13T10:46:56.826713Z",
     "start_time": "2025-06-13T10:46:56.820491Z"
    }
   },
   "source": [
    "# 多级排序\n",
    "students = [(\"Zhouyu\", 25), (\"Dadudu\", 23), (\"Xiaodudu\", 23)]\n",
    "students.sort(key=lambda x: (x[1], x[0]))  # 先按年龄，再按姓名\n",
    "print(students)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('Dadudu', 23), ('Xiaodudu', 23), ('Zhouyu', 25)]\n"
     ]
    }
   ],
   "execution_count": 94
  },
  {
   "cell_type": "code",
   "id": "81d4a7e0c97a36e",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": [],
    "ExecuteTime": {
     "end_time": "2025-06-13T10:47:19.228012Z",
     "start_time": "2025-06-13T10:47:19.225741Z"
    }
   },
   "source": [
    "# 使用sorted()函数创建新排序列表\n",
    "original = [3, 1, 4]\n",
    "new_sorted = sorted(original)\n",
    "print(original)  # (未改变)\n",
    "print(new_sorted)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[3, 1, 4]\n",
      "[1, 3, 4]\n"
     ]
    }
   ],
   "execution_count": 95
  },
  {
   "cell_type": "markdown",
   "id": "cf3a93419268ca0c",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 列表合并与扩展"
   ]
  },
  {
   "cell_type": "code",
   "id": "79d7eb92dc6d8785",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T10:47:48.687951Z",
     "start_time": "2025-06-13T10:47:48.674569Z"
    }
   },
   "source": [
    "# 使用+合并列表\n",
    "list1 = [1, 2, 3]\n",
    "list2 = [4, 5, 6]\n",
    "\n",
    "combined = list1 + list2\n",
    "print(combined)\n",
    "print(list1)\n",
    "print(list2)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4, 5, 6]\n",
      "[1, 2, 3]\n",
      "[4, 5, 6]\n"
     ]
    }
   ],
   "execution_count": 96
  },
  {
   "cell_type": "code",
   "id": "1fa1da87d7d523fa",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": [],
    "ExecuteTime": {
     "end_time": "2025-06-13T10:47:57.325944Z",
     "start_time": "2025-06-13T10:47:57.322700Z"
    }
   },
   "source": [
    "# 使用extend()方法\n",
    "list1.extend(list2)\n",
    "print(list1)\n",
    "print(list2)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4, 5, 6]\n",
      "[4, 5, 6]\n"
     ]
    }
   ],
   "execution_count": 97
  },
  {
   "cell_type": "code",
   "id": "a4080d751efa8df",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": [],
    "ExecuteTime": {
     "end_time": "2025-06-13T10:48:50.459260Z",
     "start_time": "2025-06-13T10:48:50.455969Z"
    }
   },
   "source": [
    "# 使用*运算符重复列表\n",
    "repeated = [0] * 5\n",
    "print(repeated)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0, 0, 0, 0, 0]\n"
     ]
    }
   ],
   "execution_count": 100
  },
  {
   "cell_type": "markdown",
   "id": "bc1b5c011cd2016e",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 列表解包(Unpacking)"
   ]
  },
  {
   "cell_type": "code",
   "id": "6d5bcbe0046a855",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T10:50:11.017112Z",
     "start_time": "2025-06-13T10:50:11.013641Z"
    }
   },
   "source": [
    "# 基本解包\n",
    "first, second, *rest = [1, 2, 3, 4, 5]\n",
    "print(first)\n",
    "print(second)\n",
    "print(rest)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n",
      "[3, 4, 5]\n"
     ]
    }
   ],
   "execution_count": 103
  },
  {
   "cell_type": "code",
   "id": "a7c78838c0862dd4",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": [],
    "ExecuteTime": {
     "end_time": "2025-06-13T10:50:57.722911Z",
     "start_time": "2025-06-13T10:50:57.720310Z"
    }
   },
   "source": [
    "# 忽略某些元素\n",
    "a, _, b, *rest = [1, 2, 3, 4, 5, 6]\n",
    "print(a, b, rest)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 3 2 [4, 5, 6]\n"
     ]
    }
   ],
   "execution_count": 106
  },
  {
   "cell_type": "code",
   "id": "320dfb953330bdfa",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": [],
    "ExecuteTime": {
     "end_time": "2025-06-13T10:52:21.521669Z",
     "start_time": "2025-06-13T10:52:21.518577Z"
    }
   },
   "source": [
    "# 嵌套解包\n",
    "x, (y, z), w = [1, [2, 3], 4]\n",
    "print(x, y, z, w)  # 1 2 3 4"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 2 3 4\n"
     ]
    }
   ],
   "execution_count": 111
  },
  {
   "cell_type": "markdown",
   "id": "7280a9f29ac51f10",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 列表推导式（List Comprehension）"
   ]
  },
  {
   "cell_type": "code",
   "id": "5ad46a9bd202eece",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": [],
    "ExecuteTime": {
     "end_time": "2025-06-13T10:52:57.010600Z",
     "start_time": "2025-06-13T10:52:57.003755Z"
    }
   },
   "source": [
    "# 基本列表推导式\n",
    "numbers = [x for x in range(10)]\n",
    "print(numbers)\n",
    "\n",
    "squares = [x ** 2 for x in range(10)]\n",
    "print(squares)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
      "[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]\n"
     ]
    }
   ],
   "execution_count": 112
  },
  {
   "cell_type": "code",
   "id": "93520e44d713f835",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": [],
    "ExecuteTime": {
     "end_time": "2025-06-13T10:56:18.431822Z",
     "start_time": "2025-06-13T10:56:18.426261Z"
    }
   },
   "source": [
    "# 带条件的列表推导式\n",
    "even_squares = [x ** 2 for x in range(10) if x % 2 == 0]\n",
    "print(even_squares)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0, 4, 16, 36, 64]\n"
     ]
    }
   ],
   "execution_count": 118
  },
  {
   "cell_type": "code",
   "id": "e396e02c3f18a6a5",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": [],
    "ExecuteTime": {
     "end_time": "2025-06-13T10:55:19.382013Z",
     "start_time": "2025-06-13T10:55:19.377152Z"
    }
   },
   "source": [
    "# 嵌套列表推导式\n",
    "matrix = [[1, 2, 3], \n",
    "          [4, 5, 6], \n",
    "          [7, 8, 9]]\n",
    "result = [num for row in matrix for num in row]\n",
    "print(result)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4, 5, 6, 7, 8, 9]\n"
     ]
    }
   ],
   "execution_count": 115
  },
  {
   "cell_type": "markdown",
   "id": "8f75f0c3eb3976d2",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 列表与函数式编程"
   ]
  },
  {
   "cell_type": "code",
   "id": "4d6c90074ccb16bd",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T10:57:07.921406Z",
     "start_time": "2025-06-13T10:57:07.913455Z"
    }
   },
   "source": [
    "# 使用map函数\n",
    "numbers = [1, 2, 3, 4]\n",
    "\n",
    "squared = list(map(lambda x: x ** 2, numbers))\n",
    "print(squared)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 4, 9, 16]\n"
     ]
    }
   ],
   "execution_count": 119
  },
  {
   "cell_type": "code",
   "id": "81c599c346905915",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T10:57:17.583299Z",
     "start_time": "2025-06-13T10:57:17.576787Z"
    }
   },
   "source": [
    "# 使用filter函数\n",
    "evens = list(filter(lambda x: x % 2 == 0, numbers))\n",
    "print(evens)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2, 4]\n"
     ]
    }
   ],
   "execution_count": 120
  },
  {
   "cell_type": "markdown",
   "id": "c0ffb80d3c85c3cc",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 列表与数据结构转换"
   ]
  },
  {
   "cell_type": "code",
   "id": "b5ab00bdaf6805cb",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T10:58:01.432561Z",
     "start_time": "2025-06-13T10:58:01.427981Z"
    }
   },
   "source": [
    "# 列表转字典\n",
    "keys = ['a', 'b', 'c']\n",
    "values = [1, 2, 3]\n",
    "\n",
    "dictionary = dict(zip(keys, values))\n",
    "\n",
    "print(dictionary)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'a': 1, 'b': 2, 'c': 3}\n"
     ]
    }
   ],
   "execution_count": 121
  },
  {
   "cell_type": "code",
   "id": "8019b6b13c7de421",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T10:58:42.955155Z",
     "start_time": "2025-06-13T10:58:42.951603Z"
    }
   },
   "source": [
    "# 列表转集合(去重)\n",
    "duplicates = [1, 2, 2, 3, 3, 3]\n",
    "unique = set(duplicates)\n",
    "print(unique)  # {1, 2, 3}"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{1, 2, 3}\n"
     ]
    }
   ],
   "execution_count": 123
  },
  {
   "cell_type": "code",
   "id": "de2bb2da93665c8c",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T10:58:50.041367Z",
     "start_time": "2025-06-13T10:58:50.038902Z"
    }
   },
   "source": [
    "# 列表转字符串\n",
    "words = ['Hello', 'world']\n",
    "sentence = ' '.join(words)\n",
    "print(sentence)  # 'Hello world'"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello world\n"
     ]
    }
   ],
   "execution_count": 125
  },
  {
   "cell_type": "code",
   "id": "cd35026955fa8032",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T10:58:53.509920Z",
     "start_time": "2025-06-13T10:58:53.506484Z"
    }
   },
   "source": [
    "import array\n",
    "\n",
    "# 创建一个整数数组\n",
    "my_array = array.array('f', [1, 2, 3, 4, 5])   # 'i' 表示整数\n",
    "print(my_array)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "array('f', [1.0, 2.0, 3.0, 4.0, 5.0])\n"
     ]
    }
   ],
   "execution_count": 126
  },
  {
   "cell_type": "markdown",
   "id": "76c915ccac3e9290",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 高级查找与统计"
   ]
  },
  {
   "cell_type": "code",
   "id": "84fa73010d3a5335",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T10:59:29.147180Z",
     "start_time": "2025-06-13T10:59:29.141348Z"
    }
   },
   "source": [
    "# 使用enumerate获取索引和值\n",
    "alphas = ['a', 'b', 'c']\n",
    "for index, value in enumerate(alphas):\n",
    "    print(index, value)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 a\n",
      "1 b\n",
      "2 c\n"
     ]
    }
   ],
   "execution_count": 128
  },
  {
   "cell_type": "code",
   "id": "6662bbcf4d815780",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T10:59:44.717914Z",
     "start_time": "2025-06-13T10:59:44.711342Z"
    }
   },
   "source": [
    "# 使用count统计元素出现次数\n",
    "numbers = [1, 2, 2, 4, 5, 3]\n",
    "print(numbers.count(2))"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    }
   ],
   "execution_count": 130
  },
  {
   "cell_type": "code",
   "id": "c5aa5ae7fdebdb9a",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T10:59:51.038873Z",
     "start_time": "2025-06-13T10:59:51.034985Z"
    }
   },
   "source": [
    "# 使用index查找元素位置\n",
    "print(numbers.index(3))"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n"
     ]
    }
   ],
   "execution_count": 131
  },
  {
   "cell_type": "code",
   "id": "29bc60ec9b7c924f",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T11:00:38.000862Z",
     "start_time": "2025-06-13T11:00:37.996739Z"
    }
   },
   "source": [
    "# 使用any和all函数\n",
    "print(any(x > 2 for x in numbers))  # 至少有一个元素大于2\n",
    "print(all(x > 0 for x in numbers))  # 所有元素都大于0"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n"
     ]
    }
   ],
   "execution_count": 134
  },
  {
   "cell_type": "markdown",
   "id": "84f6f8b7e570d9f3",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "## 元组高级操作"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b8209f24893b823f",
   "metadata": {},
   "source": [
    "元组(tuple)是Python中不可变的序列类型，虽然不如列表灵活，但在某些场景下非常有用"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b0a8affb3b10ca6e",
   "metadata": {},
   "source": [
    "### 元组的不可变性"
   ]
  },
  {
   "cell_type": "code",
   "id": "ea3cbf2c469e214a",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T13:09:02.501913Z",
     "start_time": "2025-06-13T13:09:02.486768Z"
    }
   },
   "source": [
    "t = (1, 2, 3, 4)\n",
    "print(t[0])\n",
    "t[0] = 10"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n"
     ]
    },
    {
     "ename": "TypeError",
     "evalue": "'tuple' object does not support item assignment",
     "output_type": "error",
     "traceback": [
      "\u001B[0;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[0;31mTypeError\u001B[0m                                 Traceback (most recent call last)",
      "Cell \u001B[0;32mIn[136], line 3\u001B[0m\n\u001B[1;32m      1\u001B[0m t \u001B[38;5;241m=\u001B[39m (\u001B[38;5;241m1\u001B[39m, \u001B[38;5;241m2\u001B[39m, \u001B[38;5;241m3\u001B[39m, \u001B[38;5;241m4\u001B[39m)\n\u001B[1;32m      2\u001B[0m \u001B[38;5;28mprint\u001B[39m(t[\u001B[38;5;241m0\u001B[39m])\n\u001B[0;32m----> 3\u001B[0m \u001B[43mt\u001B[49m\u001B[43m[\u001B[49m\u001B[38;5;241;43m0\u001B[39;49m\u001B[43m]\u001B[49m \u001B[38;5;241m=\u001B[39m \u001B[38;5;241m10\u001B[39m\n",
      "\u001B[0;31mTypeError\u001B[0m: 'tuple' object does not support item assignment"
     ]
    }
   ],
   "execution_count": 136
  },
  {
   "cell_type": "markdown",
   "id": "81354122a4fa13d",
   "metadata": {},
   "source": [
    "### 元组解包（Tuple Unpacking）"
   ]
  },
  {
   "cell_type": "code",
   "id": "54fb3a4c5cef1165",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T13:09:15.636977Z",
     "start_time": "2025-06-13T13:09:15.630938Z"
    }
   },
   "source": [
    "# 基本解包\n",
    "a, b, c = (1, 2, 3)\n",
    "print(a, b, c)  # 输出: 1 2 3"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 2 3\n"
     ]
    }
   ],
   "execution_count": 137
  },
  {
   "cell_type": "code",
   "id": "c34ba284575eca8e",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T13:09:25.929608Z",
     "start_time": "2025-06-13T13:09:25.926805Z"
    }
   },
   "source": [
    "# 使用*收集剩余元素\n",
    "first, *middle, last = (1, 2, 3, 4, 5)\n",
    "print(first)  # 1\n",
    "print(middle)  # [2, 3, 4] (注意变成了列表)\n",
    "print(last)  # 5"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "[2, 3, 4]\n",
      "5\n"
     ]
    }
   ],
   "execution_count": 138
  },
  {
   "cell_type": "markdown",
   "id": "b8d0b17c62f14647",
   "metadata": {},
   "source": [
    "### 元组作为字典键"
   ]
  },
  {
   "cell_type": "code",
   "id": "8dacf67179e7d641",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T13:10:42.355994Z",
     "start_time": "2025-06-13T13:10:42.353887Z"
    }
   },
   "source": [
    "# 元组可以作为字典键，而列表不行\n",
    "locations = {\n",
    "    (11.1111, 22.2222): \"Beijing\",\n",
    "    (55.5555, 66.6666): \"Changsha\"\n",
    "}\n",
    "\n",
    "# locations = {\n",
    "#     [11.1111, 22.2222]: \"Beijing\"\n",
    "# }\n",
    "\n",
    "print(locations[(11.1111, 22.2222)])"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Beijing\n"
     ]
    }
   ],
   "execution_count": 141
  },
  {
   "cell_type": "markdown",
   "id": "9875abd70c249f72",
   "metadata": {},
   "source": [
    "### 元组与函数的配合"
   ]
  },
  {
   "cell_type": "code",
   "id": "e88a4171e801d91",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T13:13:23.567833Z",
     "start_time": "2025-06-13T13:13:23.562244Z"
    }
   },
   "source": [
    "# 函数返回多个值实际上是返回元组\n",
    "def min_max(items):\n",
    "    return min(items), max(items)\n",
    "\n",
    "\n",
    "lower, upper = min_max([4, 2, 7, 1, 9])\n",
    "print(lower, upper)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 9\n"
     ]
    }
   ],
   "execution_count": 4
  },
  {
   "cell_type": "markdown",
   "id": "c4b73bff66901571",
   "metadata": {},
   "source": "### 元组推导式"
  },
  {
   "cell_type": "code",
   "id": "6c41a7113445c7fb",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T13:13:35.904280Z",
     "start_time": "2025-06-13T13:13:35.901056Z"
    }
   },
   "source": [
    "# 使用生成器表达式创建元组\n",
    "t = tuple(x * 2 for x in range(5))\n",
    "print(t)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(0, 2, 4, 6, 8)\n"
     ]
    }
   ],
   "execution_count": 5
  },
  {
   "cell_type": "markdown",
   "id": "736b27bea57e1db5",
   "metadata": {},
   "source": [
    "### 元组与zip函数"
   ]
  },
  {
   "cell_type": "code",
   "id": "47148b9ec7449ff0",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T13:23:54.460657Z",
     "start_time": "2025-06-13T13:23:54.450144Z"
    }
   },
   "source": [
    "names = ('Zhouyu', 'Dadudu', 'Xiaodudu')\n",
    "scores = (85, 92, 78)\n",
    "\n",
    "# 压缩之后得到一个元组\n",
    "combined = tuple(zip(names, scores))\n",
    "print(combined)\n",
    "\n",
    "# 压缩之后得到一个list\n",
    "# combined = list(zip(names, scores))\n",
    "# print(combined)\n",
    "\n",
    "# # 压缩之后得到一个dict\n",
    "# combined = dict(zip(names, scores))\n",
    "# print(combined)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(('Zhouyu', 85), ('Dadudu', 92), ('Xiaodudu', 78))\n"
     ]
    }
   ],
   "execution_count": 22
  },
  {
   "cell_type": "code",
   "id": "432c431ae5652961",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T13:23:56.307585Z",
     "start_time": "2025-06-13T13:23:56.304636Z"
    }
   },
   "source": [
    "# 解压\n",
    "names_back = zip(*combined)  # zip('Zhouyu', 'Dadudu', 'Xiaodudu')\n",
    "print(list(names_back))\n",
    "# print(scores_back)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('Zhouyu', 'Dadudu', 'Xiaodudu'), (85, 92, 78)]\n"
     ]
    }
   ],
   "execution_count": 23
  },
  {
   "cell_type": "markdown",
   "id": "33eb1b559048d5a",
   "metadata": {},
   "source": [
    "### 元组的内存效率"
   ]
  },
  {
   "cell_type": "code",
   "id": "45290954544fbaa5",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T13:24:08.749391Z",
     "start_time": "2025-06-13T13:24:08.744994Z"
    }
   },
   "source": [
    "import sys\n",
    "\n",
    "# 元组比列表占用更少内存\n",
    "list_ex = [1, 2, 3]\n",
    "tuple_ex = (1, 2, 3)\n",
    "\n",
    "print(sys.getsizeof(list_ex))  # 可能因系统而异\n",
    "print(sys.getsizeof(tuple_ex))"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "88\n",
      "64\n"
     ]
    }
   ],
   "execution_count": 24
  },
  {
   "cell_type": "markdown",
   "id": "dc96dccc9c5f4998",
   "metadata": {},
   "source": [
    "## 字典高级操作"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "994dcb052fc7e200",
   "metadata": {},
   "source": [
    "### 字典推导式（Dictionary Comprehension）"
   ]
  },
  {
   "cell_type": "code",
   "id": "8beb89206f0e3c98",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T13:56:12.178165Z",
     "start_time": "2025-06-13T13:56:12.162206Z"
    }
   },
   "source": [
    "# 基本字典推导式\n",
    "squares = {x: x * 2 for x in range(5)}\n",
    "print(squares)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{0: 0, 1: 2, 2: 4, 3: 6, 4: 8}\n"
     ]
    }
   ],
   "execution_count": 25
  },
  {
   "cell_type": "code",
   "id": "75743791240dd827",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T13:56:27.738010Z",
     "start_time": "2025-06-13T13:56:27.733331Z"
    }
   },
   "source": [
    "# 带条件的字典推导式\n",
    "even_squares = {x: x * 2 for x in range(10) if x % 2 == 0}\n",
    "print(even_squares)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{0: 0, 2: 4, 4: 8, 6: 12, 8: 16}\n"
     ]
    }
   ],
   "execution_count": 26
  },
  {
   "cell_type": "code",
   "id": "d6b3d69761a16fb3",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T13:56:59.904198Z",
     "start_time": "2025-06-13T13:56:59.900406Z"
    }
   },
   "source": [
    "# 从两个列表创建字典\n",
    "keys = ['a', 'b', 'c']\n",
    "values = [1, 2, 3]\n",
    "d = {k: v for k, v in zip(keys, values)}\n",
    "print(d)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'a': 1, 'b': 2, 'c': 3}\n"
     ]
    }
   ],
   "execution_count": 27
  },
  {
   "cell_type": "markdown",
   "id": "e5bbc7d0f340439b",
   "metadata": {},
   "source": [
    "### 合并字典"
   ]
  },
  {
   "cell_type": "code",
   "id": "565f94a9100877cb",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T13:57:36.823636Z",
     "start_time": "2025-06-13T13:57:36.820139Z"
    }
   },
   "source": [
    "# 使用 ** 解包\n",
    "d1 = {'a': 1, 'b': 2}\n",
    "d2 = {'b': 3, 'c': 4}\n",
    "merged = {**d1, **d2}  # 后面的字典覆盖前面的\n",
    "print(d1)\n",
    "print(d2)\n",
    "print(merged)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'a': 1, 'b': 2}\n",
      "{'b': 3, 'c': 4}\n",
      "{'a': 1, 'b': 3, 'c': 4}\n"
     ]
    }
   ],
   "execution_count": 29
  },
  {
   "cell_type": "code",
   "id": "fd2d11a450511c83",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T13:57:48.255684Z",
     "start_time": "2025-06-13T13:57:48.252232Z"
    }
   },
   "source": [
    "# 使用update方法(原地修改)\n",
    "d1.update(d2)\n",
    "print(d1)\n",
    "print(d2)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'a': 1, 'b': 3, 'c': 4}\n",
      "{'b': 3, 'c': 4}\n"
     ]
    }
   ],
   "execution_count": 30
  },
  {
   "cell_type": "markdown",
   "id": "5701dc4e63568d0f",
   "metadata": {},
   "source": [
    "### 字典视图对象"
   ]
  },
  {
   "cell_type": "code",
   "id": "66158d31518b4048",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T13:59:12.229345Z",
     "start_time": "2025-06-13T13:59:12.225151Z"
    }
   },
   "source": [
    "d = {'a': 1, 'b': 2, 'c': 3}\n",
    "\n",
    "# 获取键、值、键值对视图\n",
    "keys = d.keys()\n",
    "values = d.values()\n",
    "items = d.items()\n",
    "print(list(keys))\n",
    "print(list(values))\n",
    "print(list(items)) # entry"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['a', 'b', 'c']\n",
      "[1, 2, 3]\n",
      "[('a', 1), ('b', 2), ('c', 3)]\n"
     ]
    }
   ],
   "execution_count": 34
  },
  {
   "cell_type": "code",
   "id": "b950537c7e45cbd4",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T13:59:41.691790Z",
     "start_time": "2025-06-13T13:59:41.687095Z"
    }
   },
   "source": [
    "# 视图是动态的\n",
    "d['d'] = 4\n",
    "print(list(keys))"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['a', 'b', 'c', 'd']\n"
     ]
    }
   ],
   "execution_count": 35
  },
  {
   "cell_type": "markdown",
   "id": "243c6c382ac4befd",
   "metadata": {},
   "source": [
    "### 有序字典(OrderedDict)"
   ]
  },
  {
   "cell_type": "code",
   "id": "26302fe2ab0a919e",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T14:00:53.195598Z",
     "start_time": "2025-06-13T14:00:53.191361Z"
    }
   },
   "source": [
    "from collections import OrderedDict\n",
    "\n",
    "# 保持插入顺序\n",
    "od = OrderedDict()\n",
    "od['a'] = 1\n",
    "od['c'] = 3\n",
    "od['b'] = 2\n",
    "print(list(od.items()))"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('a', 1), ('c', 3), ('b', 2)]\n"
     ]
    }
   ],
   "execution_count": 38
  },
  {
   "cell_type": "code",
   "id": "cb1c5d054e35b77b",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T14:01:25.482873Z",
     "start_time": "2025-06-13T14:01:25.479289Z"
    }
   },
   "source": [
    "# 移动元素到最后\n",
    "od.move_to_end('a')\n",
    "print(list(od.items()))"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('c', 3), ('b', 2), ('a', 1)]\n"
     ]
    }
   ],
   "execution_count": 39
  },
  {
   "cell_type": "code",
   "id": "7ae203ce72a5c88b",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T14:02:02.369267Z",
     "start_time": "2025-06-13T14:02:02.366160Z"
    }
   },
   "source": [
    "# 弹出最后/最前的元素\n",
    "od.popitem(last=False)  # 移除第一个\n",
    "print(od)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OrderedDict([('b', 2)])\n"
     ]
    }
   ],
   "execution_count": 41
  },
  {
   "cell_type": "markdown",
   "id": "a2c6d0a6ef073cf1",
   "metadata": {},
   "source": [
    "### 字典排序"
   ]
  },
  {
   "cell_type": "code",
   "id": "18eea028db32f038",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T14:04:49.671813Z",
     "start_time": "2025-06-13T14:04:49.667045Z"
    }
   },
   "source": [
    "# 按键排序\n",
    "d = {'b': 2, 'a': 4, 'c': 3}\n",
    "\n",
    "sorted_by_key = {k: d[k] for k in sorted(d.keys())}\n",
    "print(sorted_by_key)\n",
    "\n",
    "# 按值排序\n",
    "sorted_by_value = {k: v for k, v in sorted(d.items(), key=lambda item: item[1])}\n",
    "print(sorted_by_value)\n",
    "\n",
    "# 多条件排序\n",
    "d = {'a': 2, 'b': 1, 'c': 2}\n",
    "sorted_dict = dict(sorted(d.items(), key=lambda x: (x[1], x[0])))\n",
    "print(sorted_dict)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'a': 4, 'b': 2, 'c': 3}\n",
      "{'b': 2, 'c': 3, 'a': 4}\n",
      "{'b': 1, 'a': 2, 'c': 2}\n"
     ]
    }
   ],
   "execution_count": 44
  },
  {
   "cell_type": "markdown",
   "id": "a1f39fbffdb9d7fd",
   "metadata": {},
   "source": [
    "## 集合高级操作"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "211746c039af7436",
   "metadata": {},
   "source": [
    "### 集合推导式"
   ]
  },
  {
   "cell_type": "code",
   "id": "dfb77853ec3362e1",
   "metadata": {},
   "source": [
    "# 基本集合推导式\n",
    "squares = {x ** 2 for x in range(5)}\n",
    "print(squares)\n",
    "\n",
    "# 带条件的集合推导式\n",
    "odd_squares = {x ** 2 for x in range(10) if x % 2 != 0}\n",
    "print(odd_squares)\n",
    "\n",
    "# 从列表创建集合(去重)\n",
    "numbers = [1, 2, 2, 3, 3, 3]\n",
    "unique_numbers = {x for x in numbers}\n",
    "print(unique_numbers)"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "markdown",
   "id": "456a105e3d6bedd4",
   "metadata": {},
   "source": [
    "### 集合运算操作"
   ]
  },
  {
   "cell_type": "code",
   "id": "d13a43990a5ff391",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T14:20:02.444558Z",
     "start_time": "2025-06-13T14:20:02.436777Z"
    }
   },
   "source": [
    "a = {1, 2, 3, 4}\n",
    "b = {3, 4, 5, 6}\n",
    "\n",
    "# 并集\n",
    "print(a | b)\n",
    "print(a.union(b))  # 同上"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{1, 2, 3, 4, 5, 6}\n",
      "{1, 2, 3, 4, 5, 6}\n"
     ]
    }
   ],
   "execution_count": 45
  },
  {
   "cell_type": "code",
   "id": "5d8dc5d4b95cd0a5",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T14:20:09.879994Z",
     "start_time": "2025-06-13T14:20:09.876620Z"
    }
   },
   "source": [
    "# 交集\n",
    "print(a & b)\n",
    "print(a.intersection(b))  # 同上"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{3, 4}\n",
      "{3, 4}\n"
     ]
    }
   ],
   "execution_count": 46
  },
  {
   "cell_type": "code",
   "id": "f6d03eb51439ab4f",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T14:20:16.813695Z",
     "start_time": "2025-06-13T14:20:16.809988Z"
    }
   },
   "source": [
    "# 差集\n",
    "print(a - b)\n",
    "print(a.difference(b))  # 同上"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{1, 2}\n",
      "{1, 2}\n"
     ]
    }
   ],
   "execution_count": 47
  },
  {
   "cell_type": "code",
   "id": "e46c22d8aade2ca0",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T14:20:33.802669Z",
     "start_time": "2025-06-13T14:20:33.798811Z"
    }
   },
   "source": [
    "x = {1, 2, 3}\n",
    "y = {1, 2}\n",
    "z = {1, 2, 3, 4}\n",
    "\n",
    "# 子集判断\n",
    "print(y <= x)  # y是x的子集\n",
    "print(y.issubset(x))  # 同上"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n"
     ]
    }
   ],
   "execution_count": 48
  },
  {
   "cell_type": "code",
   "id": "1d7061ff47c1970c",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T14:20:42.430726Z",
     "start_time": "2025-06-13T14:20:42.426456Z"
    }
   },
   "source": [
    "# 超集判断\n",
    "print(x >= y)  # x是y的超集\n",
    "print(x.issuperset(y))  # 同上"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n"
     ]
    }
   ],
   "execution_count": 49
  },
  {
   "cell_type": "markdown",
   "id": "5371d14effbb6d2b",
   "metadata": {},
   "source": [
    "### 集合更新操作"
   ]
  },
  {
   "cell_type": "code",
   "id": "a14c40a9860e859a",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T14:20:56.471741Z",
     "start_time": "2025-06-13T14:20:56.468201Z"
    }
   },
   "source": [
    "s = {1, 2, 3}\n",
    "\n",
    "# 添加元素\n",
    "s.add(4)\n",
    "print(s)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{1, 2, 3, 4}\n"
     ]
    }
   ],
   "execution_count": 50
  },
  {
   "cell_type": "code",
   "id": "9a139d7177b4f2d6",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T14:21:31.080687Z",
     "start_time": "2025-06-13T14:21:31.078680Z"
    }
   },
   "source": [
    "# 添加多个元素\n",
    "s.update([5, 6], [7, 8])\n",
    "print(s)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{1, 2, 3, 4, 5, 6, 7, 8}\n"
     ]
    }
   ],
   "execution_count": 53
  },
  {
   "cell_type": "code",
   "id": "2e4c55f5821928b3",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T14:21:43.015808Z",
     "start_time": "2025-06-13T14:21:43.012374Z"
    }
   },
   "source": [
    "# 移除元素\n",
    "s.discard(8)  # 安全移除，不存在不报错\n",
    "s.remove(7)  # 移除，不存在会报KeyError\n",
    "print(s)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{1, 2, 3, 4, 5, 6}\n"
     ]
    }
   ],
   "execution_count": 54
  },
  {
   "cell_type": "code",
   "id": "2bb411ed563389c2",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T14:22:00.581604Z",
     "start_time": "2025-06-13T14:22:00.578849Z"
    }
   },
   "source": [
    "# 随机弹出元素\n",
    "popped = s.pop()\n",
    "print(f\"弹出: {popped}, 剩余: {s}\")"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "弹出: 3, 剩余: {4, 5, 6}\n"
     ]
    }
   ],
   "execution_count": 57
  },
  {
   "cell_type": "code",
   "id": "23377a1f47c7d6aa",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T14:22:05.810600Z",
     "start_time": "2025-06-13T14:22:05.807823Z"
    }
   },
   "source": [
    "# 清空集合\n",
    "s.clear()\n",
    "print(s)  # set()"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "set()\n"
     ]
    }
   ],
   "execution_count": 58
  },
  {
   "cell_type": "markdown",
   "id": "df262110cf863d21",
   "metadata": {},
   "source": [
    "### 不可变集合(frozenset)"
   ]
  },
  {
   "cell_type": "code",
   "id": "f2e44a0bb990835e",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T14:22:50.575017Z",
     "start_time": "2025-06-13T14:22:50.572216Z"
    }
   },
   "source": [
    "# 创建不可变集合\n",
    "fs = frozenset([1, 2, 3, 2])\n",
    "print(fs)\n",
    "\n",
    "# 不可变集合可以作为字典键\n",
    "d = {fs: \"123\"}\n",
    "print(d[frozenset([1, 2, 3])])\n",
    "\n",
    "# 不可变集合支持集合运算但不能修改\n",
    "fs2 = frozenset([3, 4, 5])\n",
    "print(fs & fs2)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "frozenset({1, 2, 3})\n",
      "123\n",
      "frozenset({3})\n"
     ]
    }
   ],
   "execution_count": 63
  },
  {
   "cell_type": "markdown",
   "id": "eb9f00d258630b52",
   "metadata": {},
   "source": [
    "### 集合与其它数据结构的转换"
   ]
  },
  {
   "cell_type": "code",
   "id": "8b695967a3930a49",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T14:23:31.524954Z",
     "start_time": "2025-06-13T14:23:31.521677Z"
    }
   },
   "source": [
    "# 集合与列表转换\n",
    "lst = [1, 2, 2, 3]\n",
    "s = set(lst)\n",
    "print(s)\n",
    "\n",
    "back_to_list = list(s)\n",
    "print(back_to_list)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{1, 2, 3}\n",
      "[1, 2, 3]\n"
     ]
    }
   ],
   "execution_count": 65
  },
  {
   "cell_type": "code",
   "id": "820953e5ab82ab3d",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T14:23:36.391615Z",
     "start_time": "2025-06-13T14:23:36.387929Z"
    }
   },
   "source": [
    "# 集合与元组转换\n",
    "t = (1, 2, 2, 3)\n",
    "s_from_tuple = set(t)\n",
    "print(s_from_tuple)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{1, 2, 3}\n"
     ]
    }
   ],
   "execution_count": 66
  },
  {
   "cell_type": "code",
   "id": "ebcee9c9ddd9edc5",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T14:23:50.393254Z",
     "start_time": "2025-06-13T14:23:50.389621Z"
    }
   },
   "source": [
    "# 集合与字典转换(只保留键)\n",
    "d = {'a': 1, 'b': 2}\n",
    "s_from_dict = set(d)\n",
    "print(s_from_dict)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'a', 'b'}\n"
     ]
    }
   ],
   "execution_count": 67
  },
  {
   "cell_type": "markdown",
   "id": "cc7f15ff112aed32",
   "metadata": {},
   "source": [
    "### 词频统计"
   ]
  },
  {
   "cell_type": "code",
   "id": "41f53426114c83ca",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T14:24:25.218250Z",
     "start_time": "2025-06-13T14:24:25.214697Z"
    }
   },
   "source": [
    "text = \"this is a sample text with several words and some repeated words\"\n",
    "words = text.split()\n",
    "print(words)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['this', 'is', 'a', 'sample', 'text', 'with', 'several', 'words', 'and', 'some', 'repeated', 'words']\n"
     ]
    }
   ],
   "execution_count": 68
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T14:24:37.204665Z",
     "start_time": "2025-06-13T14:24:37.200695Z"
    }
   },
   "cell_type": "code",
   "source": [
    "unique_words = set(words)\n",
    "word_count = len(unique_words)\n",
    "print(f\"唯一单词数: {word_count}\")"
   ],
   "id": "c620aa883e168600",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "唯一单词数: 11\n"
     ]
    }
   ],
   "execution_count": 69
  },
  {
   "cell_type": "markdown",
   "id": "3320a828771583",
   "metadata": {},
   "source": [
    "## 类与函数"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ea6b05a05aa6fa2f",
   "metadata": {},
   "source": [
    "### 定义函数"
   ]
  },
  {
   "cell_type": "code",
   "id": "94d5538b22ce69f2",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T14:37:20.146772Z",
     "start_time": "2025-06-13T14:37:20.139309Z"
    }
   },
   "source": [
    "def greet(name):\n",
    "    \"\"\"这是一个简单的问候函数\"\"\"\n",
    "    return f\"Hello, {name}!\"\n",
    "\n",
    "\n",
    "# 调用函数\n",
    "message = greet(\"Zhouyu\")\n",
    "print(message)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello, Zhouyu!\n"
     ]
    }
   ],
   "execution_count": 70
  },
  {
   "cell_type": "markdown",
   "id": "1629f052899a6258",
   "metadata": {},
   "source": [
    "### 定义类"
   ]
  },
  {
   "cell_type": "code",
   "id": "1f4ea7074b77ec22",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T14:37:48.062132Z",
     "start_time": "2025-06-13T14:37:48.058123Z"
    }
   },
   "source": [
    "class Dog:\n",
    "    # 构造方法、初始化方法\n",
    "    def __init__(self, name, age):\n",
    "        self.name = name\n",
    "        self.age = age\n",
    "\n",
    "    # 实例方法\n",
    "    def description(self):\n",
    "        return f\"{self.name}现在{self.age}岁\"\n",
    "\n",
    "    # 另一个实例方法\n",
    "    def speak(self, sound):\n",
    "        return f\"{self.name}说{sound}\"\n",
    "\n",
    "\n",
    "buddy = Dog(\"旺财\", 5)\n",
    "print(buddy.description())\n",
    "print(buddy.speak(\"Hi\"))"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "旺财现在5岁\n",
      "旺财说Hi\n"
     ]
    }
   ],
   "execution_count": 71
  },
  {
   "cell_type": "markdown",
   "id": "f6281cf75d45bb0e",
   "metadata": {},
   "source": [
    "### 继承"
   ]
  },
  {
   "cell_type": "code",
   "id": "c64f0009c3043528",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T14:38:17.311201Z",
     "start_time": "2025-06-13T14:38:17.306891Z"
    }
   },
   "source": [
    "class Bulldog(Dog):  # 继承Dog类\n",
    "    def run(self, speed):\n",
    "        return f\"{self.name}跑起来很快，速度是{speed}\"\n",
    "\n",
    "# 创建子类实例\n",
    "jim = Bulldog(\"大黄\", 3)\n",
    "print(jim.speak(\"Hello\"))  # 继承父类方法\n",
    "print(jim.run(12))"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "大黄说Hello\n",
      "大黄跑起来很快，速度是12\n"
     ]
    }
   ],
   "execution_count": 72
  },
  {
   "cell_type": "markdown",
   "id": "592b940c386fe2f3",
   "metadata": {},
   "source": [
    "### 特殊方法"
   ]
  },
  {
   "cell_type": "code",
   "id": "4575f0d730ca60c5",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-13T14:39:19.774391Z",
     "start_time": "2025-06-13T14:39:19.769815Z"
    }
   },
   "source": [
    "class Book:\n",
    "    def __init__(self, title, author, pages):\n",
    "        self.title = title\n",
    "        self.author = author\n",
    "        self.pages = pages\n",
    "\n",
    "    # 字符串表示\n",
    "    def __str__(self):\n",
    "        return f\"{self.title}的作者是{self.author}\"\n",
    "\n",
    "    # 长度\n",
    "    def __len__(self):\n",
    "        return self.pages\n",
    "\n",
    "# 三国演义的作者是\n",
    "book = Book(\"三国演义\", \"罗贯中\", 200)\n",
    "print(book)\n",
    "print(len(book))"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "三国演义的作者是罗贯中\n",
      "200\n"
     ]
    }
   ],
   "execution_count": 78
  }
 ],
 "metadata": {
  "@deathbeds/jupyterlab-fonts": {
   "styles": {
    ":root": {
     "--jp-code-font-size": "22px",
     "--jp-content-font-size1": "32px"
    }
   }
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
